<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
session_start();

class login extends CI_Controller {

    var $logged_in = false;
    var $session_data;

    public function __construct() {
        parent::__construct();
        if ($this->session->userdata('logged_in_user')) {
            $data['user'] = $this->session->userdata('logged_in_user');
            $this->logged_in = true;
            $this->session_data = $data;
        }
        $this->load->model('Dao');
    }

    public function index() {
        if ($this->logged_in) {
            redirect("chat/index");
        } else {
            $data['title'] = 'Welcome to wfaces';
            $data['description'] = 'NONE';
            $data['keywords'] = 'Key, words, of, the, page';
            $data['view'] = 'v_login';
            $this->load->view('templates/loginTemplate', $data);
            // $this->load->view('v_login');
        }
    }

    public function verifLogin() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
        if ($this->form_validation->run() == FALSE) {
            //Field validation failed.  User redirected to login page
            $this->load->view('v_login');
        } else {
            $login = $this->input->post("login");
            $pass = $this->input->post("password");
            $ok = $this->Dao->verifOnDb($login, $pass);
            if ($ok) {
                $this->back();
                redirect('chat/', 'refresh');
            } else {
                $this->form_validation->set_message('check_database', 'Invalid username or password');
                $data['title'] = 'Welcome to wfaces';
                $data['description'] = 'NONE';
                $data['keywords'] = 'Key, words, of, the, page';
                $data['view'] = 'v_login';
                $this->load->view('templates/loginTemplate', $data);
            }
        }
    }

    public function logout() {
        if ($this->logged_in) {
            $id = $this->session->userdata('logged_in_user')->id;
            $this->session->unset_userdata('logged_in_user');
            $this->session->unset_userdata('connections');
            session_destroy();
            $this->logged_in = false;
            $this->Dao->toOffline($id);
            $data['title'] = 'Welcome to wfaces';
            $data['description'] = 'NONE';
            $data['keywords'] = 'Key, words, of, the, page';
            $data['view'] = 'v_login';
            $this->load->view('templates/loginTemplate', $data);
        }
    }

    public function idle() {
        $this->Dao->goIdle();
    }

    public function back() {
        $this->Dao->goOnline();
    }

}

